package com.zhkc.wisdom.common.mybatis.encrypt.utils;

import com.zhkc.wisdom.common.mybatis.encrypt.annotation.EncryptField;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.Objects;

/**
 * .
 *
 * @author kehong liu 2021/12/16.
 */
public final class EncryptUtil {

	private EncryptUtil() {
	}

	public static <T> void encrypt(Field[] declaredFields, T paramsObject, String key) throws Exception {
		for (Field field : declaredFields) {
			// 取出所有被EncryptField注解的字段
			EncryptField sensitiveField = field.getAnnotation(EncryptField.class);
			if (!Objects.isNull(sensitiveField)) {
				ReflectionUtils.makeAccessible(field);
				Object object = field.get(paramsObject);
				// 暂时只实现String类型的加密
				if (object instanceof String) {
					String value = (String) object;
					ReflectionUtils.setField(field, paramsObject, AesKeyUtils.encrypt(value, key));
				}
			}
		}
	}

	public static void decrypt(Object result, String key) throws Exception {
		Class<?> resultClass = result.getClass();
		Field[] fields = resultClass.getDeclaredFields();
		for (Field field : fields) {
			EncryptField annotation = field.getAnnotation(EncryptField.class);
			if (Objects.nonNull(annotation)) {
				ReflectionUtils.makeAccessible(field);
				Object fieldInstance = field.get(result);
				if (fieldInstance instanceof String) {
					ReflectionUtils.setField(field, result, AesKeyUtils.decrypt((String) fieldInstance, key));
				}
			}
		}
	}

}
